package pl.vm.domain;

import java.util.HashSet;
import java.util.Set;

import pl.vm.domain.exceptions.InvalidStateException;
import pl.vm.domain.exceptions.RoundAlreadyExistsException;
import pl.vm.domain.interfaces.Round;
import pl.vm.domain.interfaces.RoundManager;
import pl.vm.utils.ObjectCloner;

public class RoundManagerImpl implements RoundManager {

	private Set<Round> rounds = new HashSet<>();
	private Round currentRound = null;
	private Seazon seazon;
	
	public RoundManagerImpl(Seazon seazon) {
		this.seazon = seazon;
	}
	
	@Override
	public Round createNewRound(int roundNumber) throws RoundAlreadyExistsException {
		Round r = getRound(roundNumber);
		if (r != null) {
			throw new RoundAlreadyExistsException("Round: " + roundNumber + " alredy exist in current seazon.");
		}
		Round newRound = new RoundImpl(seazon.new SeazonLoopbackImpl(), roundNumber);
		currentRound = newRound;
		rounds.add(newRound);
		for (VirtualTeam team : seazon.getTeamManager().getVirtualTeams()) {
			addTeamToCurrentRound(team);
		}
		return newRound;
	}

	private boolean addTeamToCurrentRound(VirtualTeam team) {
		if (currentRound != null && team.isTeamRegistered()) {
			try {
				return currentRound.addTeam((VirtualTeam) ObjectCloner.deepCopy(team));
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}	
	
	@Override
	public Set<Round> getRounds() {
		return rounds;
	}

	@Override
	public Round getRound(int roundNumber) {
		for (Round round : rounds) {
			if (round.getNumber() == roundNumber) {
				return round;
			}
		}
		return null;
	}

	@Override
	public void closeRound(int roundNumber) throws InvalidStateException {
		Round round = getRound(roundNumber);
		round.close();
	}

	@Override
	public Round getCurrentRound() {
		return currentRound;
	}

}
